package beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;


import dataStorage.DBData;

@ManagedBean(name="regBean")
@SessionScoped
public class RegisterBean {

	private String username;
	private String password;
	private String message;
	
	public RegisterBean(){
		username = "";
		password = "";
		message = "";
	}
	public RegisterBean(String username, String password){
		this.username = username;
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	public synchronized String registerUser(){
			Connection conn = null;
			try {
				conn = DBData.getConnection();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			String query = "INSERT INTO ZUSER (UNAM, PASS) VALUES ('" + username + "', '" + password + "')" ;	
			try {
				PreparedStatement ps = conn.prepareStatement(query);
				ps.execute();
			} catch (SQLException e) {
				e.printStackTrace();
				message = e.toString();
				return "failure";
			}
			
			FacesContext facesCtx = FacesContext.getCurrentInstance();
			ExternalContext extCtx = facesCtx.getExternalContext();

			
			User u = (User)extCtx.getSessionMap().get("userBean");
			u.setUsername(username);
			username = "";
			message = "registered";
			return message;
	}
}
